import 'miniprogram-api-typings'
import { AdvertType, gameEvent, GameEventType, RankMesgType } from './Global';

export class WXUtils {
    // 保存游戏圈按钮
    static gameClubButton: any = null
    // 广告实例
    static videoAd: any

    // 创建游戏圈按钮
    static createGameClubButton(): void {
        const wx = window['wx']
        console.log('wx:', wx);

        if (!wx) return;
        if (WXUtils.gameClubButton) return;

        const { screenWidth, screenHeight } = wx.getWindowInfo()
        const btnWidth = 100
        const btnHeight = 30
        const centerX = (screenWidth - btnWidth) / 2


        const config = {
            type: 'text',
            text: '游戏圈',
            style: {
                top: screenHeight - 250,
                left: centerX,
                width: btnWidth,
                height: btnHeight,
                lineHeight: btnHeight,
                textAlign: 'center',
                backgroundColor: '#0096d7',
                color: '#FFFFFF',
                fontSize: 16,
                borderRadius: 15,
                borderWidth: 1,
                borderColor: '#FFFFFF',
                zIndex: 999999
            },
            onClick: function () {
                console.log('游戏圈按钮被点击了')
            }
        }
        WXUtils.gameClubButton = wx.createGameClubButton(config)
    }

    static initShare() {
        const wx = window['wx']
        if (!wx) return;
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        // wx.shareAppMessage({
        //     imageUrlId: 'IkAqXsVUQa27W2oPz80e3g==',
        //     imageUrl: 'https://mmocgame.qpic.cn/wechatgame/7b91licRNcgySibICia0MFVeHYWjzCJe1FmfviaF1yic1JHNiaPV7rnibtibhuYkEgySJPj6/0'
        // })
    }

    static initAdvert() {
        const wx = window['wx']
        if (!wx) return;
        WXUtils.videoAd ??= wx.createRewardedVideoAd({
            adUnitId: 'adunit-4c9f0e9db7bbdfd1'
        })

        WXUtils.videoAd.onError(err => {
            console.log('xxxxxxxxxxx:', '广告显示失败2');
        })

        WXUtils.videoAd.onClose(res => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                gameEvent.emit(GameEventType.ADVERT, AdvertType.AD_SUCCESS);
                console.log('xxxxxxxxxxx:', '广告播放结束, 可以下发游戏奖励');
            }
            else {
                gameEvent.emit(GameEventType.ADVERT, AdvertType.AD_CLOSE);
                console.log('xxxxxxxxxxx:', '广告播放中途退出, 不下发游戏奖励');
            }
        })
    }
    static showVideoAd(): void {
        const wx = window['wx']
        if (!wx) return gameEvent.emit(GameEventType.ADVERT, AdvertType.AD_SUCCESS);
        // 创建激励视频广告实例，提前初始化
        WXUtils.videoAd ??= wx.createRewardedVideoAd({
            adUnitId: 'adunit-4c9f0e9db7bbdfd1'
        })

        // 用户触发广告后，显示激励视频广告
        WXUtils.videoAd.show()
            .then(() => {
                // 广告显示成功
                gameEvent.emit(GameEventType.ADVERT, AdvertType.AD_SHOW);
                console.log('xxxxxxxxxxx:', '广告显示成功');

            })
            .catch((err) => {
                // 失败重试
                gameEvent.emit(GameEventType.ADVERT, AdvertType.AD_ERROR);
                console.log('xxxxxxxxxxx:', '广告显示失败');
            })
    }

    static showToast(title: string) {
        const wx = window['wx']
        if (!wx) return;
        wx.showToast({
            title: title,
            icon: 'none',
            duration: 1000,
        })
    }

    /**
     * 监听隐私接口需要用户授权事件
     * @param callback 
     * @returns 
     */
    static onNeedPrivacyAuthorization(callback: (resolve: () => void, eventInfo: any) => void) {
        const wx = window['wx']
        if (!wx) return;
        wx.onNeedPrivacyAuthorization(callback)
    }

    static openPrivacyContract(): Promise<boolean> {
        const wx = window['wx']
        if (!wx) return Promise.resolve(false);
        return new Promise((resolve, reject) => {
            wx.getPrivacySetting({
                success: function (res) {
                    // console.log('res:', res);

                    if (!res.needAuthorization) {
                        // console.log('用户已同意隐私协议');
                        resolve(true)
                        return
                    }
                    wx.openPrivacyContract({
                        success: function () {
                            // console.log('用户同意隐私协议');
                            resolve(true)
                        },
                        fail: () => {
                            // console.log('用户拒绝隐私协议');
                            reject()
                        }
                    })
                },
                fail: () => {
                    // console.log('获取用户隐私设置失败');
                    reject()
                }
            })
        })
    }

    /**
     * 获取用户信息
     * @returns 
     */
    static getUserInfo(): Promise<any> {
        const wx = window['wx']
        if (!wx) return Promise.resolve({});
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success(res) {
                    if (res.authSetting['scope.userInfo']) {
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                        // console.log('用户已经授权，可以直接调用 getUserInfo 获取头像昵称');

                        wx.getUserInfo({
                            success: (res) => resolve(res.userInfo),
                            fail: (err) => reject(err)
                        })
                    } else {
                        const { screenWidth, screenHeight } = wx.getWindowInfo()
                        const btnWidth = 150
                        const btnHeight = 30
                        const centerX = (screenWidth - btnWidth) / 2
                        const button = wx.createUserInfoButton({
                            type: 'text',
                            text: '确认授权',
                            style: {
                                top: screenHeight - 150,
                                left: centerX,
                                width: btnWidth,
                                height: btnHeight,
                                lineHeight: btnHeight,
                                backgroundColor: '#0096d7',
                                color: '#FFFFFF',
                                textAlign: 'center',
                                fontSize: 16,
                                borderRadius: 15
                            }
                        })
                        button.onTap((res) => {
                            // 此处可以获取到用户信息
                            // console.log('用户点击了获取用户信息按钮', res);
                            resolve(res.userInfo)
                            button.hide()
                        })
                    }
                }
            })
        })
    }

    /**
     * 保存用户信息到WXStorage云端
     * @param nickName 
     * @param avatarUrl 
     * @param level 
     * @returns 
     */
    static setUserCloudStorage(data: object): Promise<boolean> {
        const wx = window['wx']
        if (!wx) return Promise.resolve(false);

        return new Promise((resolve, reject) => {
            wx.setUserCloudStorage({
                KVDataList: [{
                    key: RankMesgType.RANK_ALL,
                    value: JSON.stringify(data)
                }],
                success: () => resolve(true),
                fail: (e) => reject(e)
            })
        })
    }

    /**
     * 向开放数据域发送消息
     * @param data 
     * @returns 
     */
    static postMessage(data: any): void {
        const wx = window['wx']
        if (!wx) return;
        let openDataContext = wx.getOpenDataContext()
        openDataContext.postMessage(data)
    }

}

